<template>
<!-- 客户端模型状态 -->
  <div class="card text-center ms-2 me-4 mt-2 mb-2">
    <div class="card-body">
      <h5 class="">客户端模型接收情况</h5>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">用户</th>
              <th v-for="(user, index) in Aggclients" :key="'user_' + index" scope="col" @click="showUserInfo(index)">{{ user.name }}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>状态</td>
              <td class="text-white" v-for="(user, index) in Aggclients" :key="'user_status_' + index" :class="{ 'bg-primary-heavy': user.status, 'bg-secondary-light': !user.status }" @click="showUserInfo(index)"> {{(user.status ? '已接收' : '未接收') }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<!--           :class="{ 'bg-secondary': !state1||!state2, 'bg-primary': state1 && state2&& !button2State, 'bg-warning': state1 && state2&& button2State }"
-->
<!--服务端状态-->
   <div class="d-flex justify-content-center mt-2 mb-2">
    <div class="card mx-auto text-center ms-2 me-4 mt-2 mb-2"
         :class="{ 'bg-secondary': !state1||!Aggstates[0], 'bg-primary-heavy': state1 && Aggstates[0]&& !Aggstates[1], 'bg-warning': state1 && Aggstates[0] && Aggstates[1] }"
         style="width: 30%; aspect-ratio: 5/2;">
      <div class="card-body d-flex align-items-center justify-content-center" @click="showServerInfo">
        <h5  class="m-0 text-white">{{ serverstate }}</h5>
      </div>
    </div>
  </div>
<!-- 按钮 -->
  <div class="container" style="white-space: nowrap; height: 200px;">
    <div class="card text-center">
      <div class="card-body">
        <div class="row mt-2 mb-2">
      <div class="col">
        <button class="btn bg-primary-heavy text-white btn-lg" @click="handleButtonClick(1)" style="width: 100%; height: 100%" >接收模型</button>
      </div>
      <div class="col">
        <button class="btn btn-lg" disabled  :class="{ 'btn-warning': Aggstates[1], 'bg-primary-heavy text-white': !Aggstates[1] }" style="width: 100%; height: 100%" >
          {{ button2Text }}
        </button>
      </div>
      <div class="col">
        <button class="btn bg-primary-heavy text-white btn-lg" @click="handleButtonClick(3)" style="width: 100%; height: 100%">聚合模型</button>
      </div>
      <div class="col">
        <button class="btn bg-primary-heavy text-white btn-lg" @click="handleButtonClick(4)" style="width: 100%; height: 100%">分发模型</button>
      </div>
      <div class="col">
        <button class="btn btn-warning btn-lg" @click="handleButtonClick(5)" style="width: 100%; height: 100%">设置服务器恶意</button>
      </div>
    </div>
      </div>
    </div>
  </div>

</template>

<script setup>
import { ref,computed,onMounted,onUnmounted } from 'vue';
import {AggserverInitialEventBus, ClientInitialEventBus} from '@/views/event-bus';
import axios from "axios";
// 所有user状态为true时，state1为true
const state1 = computed(() => Aggclients.value.every(user => user.status === true));
// const state1 = ref(true);
// const state2 = ref(false);
// const state3 = ref(false);
// const button2State = ref(false); // 初始状态为 true
const button2Text = ref('服务器诚实'); // 初始文本为 '状态2'

const initialStates = [false, false,'server information']
const initialClients = [
  { name: 'user1', status: false, info: 'User 1 information' },
  { name: 'user2', status: false, info: 'User 2 information' },
  { name: 'user3', status: false, info: 'User 1 information' },
  { name: 'user4', status: false, info: 'User 2 information' },
  { name: 'user5', status: false, info: 'User 1 information' },
  { name: 'user6', status: false, info: 'User 2 information' },
  { name: 'user7', status: false, info: 'User 2 information' },
  { name: 'user8', status: false, info: 'User 2 information' },
  { name: 'user9', status: false, info: 'User 2 information' },
  { name: 'user10', status: false, info: 'User 2 information' },
]

//设置axios
const apiBaseUrl = (window.webConfig && window.webConfig.webApiBaseUrl) || process.env.VUE_APP_BACKEND_API;
const apiAgg = axios.create({
  baseURL: apiBaseUrl,
  headers: {
    'Content-Type': 'application/json'
  }
});

const Aggclients = ref([]);
const Aggstates = ref([]);
// 从本地存储中获取用户设置
const loadAggclientsFromLocalStorage = (option) => {
  if (option===1){
    const storedAggClients = JSON.parse(localStorage.getItem('Aggclients'));
    if (storedAggClients) {
      Aggclients.value = storedAggClients;
    } else {
     Aggclients.value = [...initialClients];
    }
  }
  if (option===2){
    const storedAggstates = JSON.parse(localStorage.getItem('Aggstates'));
    console.log("storedAggstates:",storedAggstates)
    if (storedAggstates) {
      Aggstates.value = storedAggstates;
      // Aggstates.value[0]= state1
    } else {
      Aggstates.value = [...initialStates];
    }
  }
};

// 将用户设置保存到本地存储
const saveAggclientsToLocalStorage = (option) => {
  if(option===1){
    // const rawAggClients = Aggclients.value.map(client => ({ ...client }));
    localStorage.setItem('Aggclients', JSON.stringify(Aggclients.value));
  }
  if(option===2){
    // const rawAggstates = Aggstates.value.map(state => ({ ...state }));
    // localStorage.setItem('Aggstates', JSON.stringify(rawAggstates));
    localStorage.setItem('Aggstates', JSON.stringify(Aggstates.value));
  }
};
// 组件挂载时加载用户设置
onMounted(() => {
  loadAggclientsFromLocalStorage(1);
  loadAggclientsFromLocalStorage(2);
  button2Text.value = Aggstates.value[1] ? '服务器恶意' : '服务器诚实';
  console.log("Aggstates",Aggstates.value);
});

// 组件卸载时保存用户设置到本地存储
onUnmounted(() => {
  saveAggclientsToLocalStorage(1);
  saveAggclientsToLocalStorage(2);

});

// 监听来自初始化按钮的事件，执行初始化操作
AggserverInitialEventBus.value.addEventListener('initializeClients', () => {
  // 重置 clients 为初始数据
  Aggclients.value = [...initialClients];
  Aggstates.value = [...initialStates];

  // 将初始数据保存到本地存储
  saveAggclientsToLocalStorage(1);
  saveAggclientsToLocalStorage(2);
  console.log("Aggclients",Aggclients.value);
  console.log("Aggstates",Aggstates.value);
});
// 监听来自初始化按钮的事件，执行初始化操作
ClientInitialEventBus.value.addEventListener('initializePages', () => {
  // 重置 clients 为初始数据
  Aggclients.value = [...initialClients];
  Aggstates.value = [...initialStates];

  // 将初始数据保存到本地存储
  saveAggclientsToLocalStorage(1);
  saveAggclientsToLocalStorage(2);
  console.log("Aggclients",Aggclients.value);
  console.log("Aggstates",Aggstates.value);
});

const showUserInfo = (index) => {
  const user = Aggclients.value[index];
  alert(user.name + " information: " + user.info);// 在真实应用中，你可以使用自定义的弹窗组件来展示用户信息
  console.log(`Clicked on column ${index}`);
};

const showServerInfo =()=>{
  alert("Server information: " + Aggstates.value[2]);// 在真实应用中，你可以使用自定义的弹窗组件来展示用户信息
  console.log(`Clicked on Server`);
}
// 根据 state1 和 state2 的值来动态计算标题的类名
// const serverstate = computed(() => {
//   if (!state1.value) {
//     return '状态1';
//   } else {
//     if(!state2.value){
//       return '状态1'; // 如果 state1 为 false，标题的类名为 m-0 text-white
//     }else{
//       if(!button2State.value){
//           return '状态2'; // 如果 state1 为 false，标题的类名为 m-0 text-white
//         }else{
//           return '状态3';
//         }
//     }
//   }
// });
const serverstate = computed(() => {
  if (!state1.value) {
    return '未聚合';
  } else {
    if(!Aggstates.value[0]){
      return '未聚合'; // 如果 state1 为 false，标题的类名为 m-0 text-white
    }else{
      if(!Aggstates.value[1]){
          return '服务器诚实'; // 如果 state1 为 false，标题的类名为 m-0 text-white
        }else{
          return '服务器恶意';
        }
    }
  }
});

let isButtonClicked = false;
const handleButtonClick = async (buttonNumber) => {
  try {
    // 检查按钮是否已经被点击，如果是，则直接返回
    if (isButtonClicked) {
      alert('正在等待上一次请求的响应，请稍后...');
      console.log('按钮已经被点击，正在等待上一次请求的响应...');
      return;
    }
    // 按钮被点击，设置状态为 true
    isButtonClicked = true;
    let response;
    switch (buttonNumber) {
      case 1:
        // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/AggServer`,{task:"server_receive_model"});
        response = await apiAgg.post(`/AggServer`,{task:"server_receive_model"});
          if (response.status === 200) {
            try {
              const updatedData = response.data.enc_w_new_s_recover;

              // const updatedData = response.data.enc_w_new_s_recover.map(base64Data => atob(base64Data));
              console.log("updatedData",updatedData);
              Aggclients.value.forEach((client, index) => {
                console.log(client.name,"updatedData",index,":",updatedData[index]);
                client.status = true
                client.info = updatedData[index] || client.info;
                // client.info = String(updatedData[index]) || client.info;

              });
              console.log("Aggclients",Aggclients.value);
              console.log("Aggstates",Aggstates.value);
              // 将初始数据保存到本地存储
              saveAggclientsToLocalStorage(1);
              saveAggclientsToLocalStorage(2);
            } catch (error) {
              console.error('解码错误：', error);
            }
          }
          console.log('按钮1的响应:', response.data);
        break;

      case 3:
        // 发送请求
        // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/AggServer`,{task:"aggregate",server_state : Aggstates.value[1] });
        response = await apiAgg.post(`/AggServer`,{task:"aggregate",server_state : Aggstates.value[1] });
        console.log(response.data);

        if (response.status === 200) {
          Aggstates.value[0]= true
          saveAggclientsToLocalStorage(2);
          if(response.data.verify_aggregation===0){
            alert("服务器聚合验证未通过，请重新开始训练")
            Aggstates.value[0]= false
          }else{
            Aggstates.value[2] = response.data.aggregation_model ||Aggstates.value[2];
             // 将初始数据保存到本地存储
              saveAggclientsToLocalStorage(2);
          }
        }
        console.log('按钮3的响应:', response.data);
        break;
      case 4:
        // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/AggServer`,{task:"set_clients"});
        response = await apiAgg.post(`/AggServer`,{task:"set_clients"});
        console.log('按钮4的响应:', response.data);
        break;
      case 5:
        Aggstates.value[1]= !Aggstates.value[1]
        button2Text.value = Aggstates.value[1] ? '服务器恶意' : '服务器诚实';
        saveAggclientsToLocalStorage(2);
        loadAggclientsFromLocalStorage(2);
        break;
      default:
        console.error('未知的按钮编号:', buttonNumber);
        break;
    }
    // 请求完成后，设置状态为 false，允许下一次点击
    isButtonClicked = false;
  } catch (error) {
    console.error('请求失败:', error);
    // 请求完成后，设置状态为 false，允许下一次点击
    isButtonClicked = false;
  }
};

</script>

<style scoped>
.bg-primary-light {
  background-color: #5e72e4 !important; /* 淡蓝色 */
}

.bg-secondary-light {
  background-color: #aba8a8 !important; /* 淡灰色 */
}
.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}
.disabled1 {
  pointer-events: none;
  opacity: 1;
}
.bg-primary-heavy {
  background-color: #152ca8 !important; /* 淡蓝色 */
}

.bg-danger-light {
  background-color: #a12004 !important; /* 淡灰色 */
}
.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}
.disabled1 {
  pointer-events: none;
  opacity: 1;
}
</style>
